package com.yz.jdd.module.cashier;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;
import com.trello.rxlifecycle.ActivityEvent;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.ExtInfo;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.cashier.scanpay.PaymentCodeActivity;
import com.yz.jdd.module.cashier.scanpay.ScanpayActivity;
import com.yz.jdd.module.main.ChooseShopActivity;
import com.yz.jdd.module.main.entity.HUABEIAMORTIZEBean;
import com.yz.jdd.module.main.entity.HuabeiService;
import com.yz.jdd.module.main.entity.ShopListItem;
import com.yz.jdd.module.scan.view.ScanActivity;
import com.yz.jdd.module.scan.view.ScanEvoucherActivity;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.network.request.Request_SetShopPay;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.keyboard.KeyboardUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.functions.Action1;

/**
 * 收银台
 *
 * @author xiongzhuang
 * @date 2019-10-12
 */
public class CashierActivity extends BaseActivity implements CashierContract.CashierView, View.OnTouchListener, View.OnClickListener {
    private Context context = CashierActivity.this;
    private TextView title;
    private TextView right_nav;

    private ImageView keyboard_show;
    //普通收银
    private LinearLayout cashierLayout;
    private EditText edt_total;//总金额
    private EditText edt_unsale;//不参与优惠金额

//    private TextView tv_promotion;//充值送活动

    private TextView tv_count_num;//计算过程记录
    //点餐收银
    private KeyboardUtil keyboard;
    private CashierContract.Presenter presenter;
    private boolean isClickable = false;//收银是否可点击
    private Request_Pay request_pay;
    private String orderType;
    private List<String> listPermission;//支付方式权限
    private List<String> btnList;//最下方支付方式列表按钮（不含扫码付款）
    private int width = 0;//屏幕宽度
    private View view_bottom;//底部占位view
    private PopupWindow paytypePopuWindow;//支付方式弹窗
    private boolean isShowPopuwindow;//是否显示
    private int keyHeigth = 107;
    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private long lastClickTime = 0;
    private long lastClickHuaBeiTime = 0;
    private RelativeLayout rl_huabei_switch;
    private SwitchButton switch_huabei;
    private RelativeLayout ll_huabei_item;
    private TextView tv_huabei1;
    private TextView tv_huabei2;
    private TextView tv_huabei3;
    private TextView tv_huabei4;
    private SoundPool soundPool;
    private Map<Integer, Integer> soundMap;

    private LinearLayout ll_no_discount;//不参与优惠金额布局

    private HuabeiService extInfo;//花呗相关信息
    private ShopListItem.ResultObjectBean.PageDataBean.ShopsBean shopsBean;
    private String[] payTypes;//支付方式

    private int keyS;//键盘类型 0 普通键盘  1 计算金额键盘

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cashier);
        initView();
    }

    void initView() {
        request_pay = (Request_Pay) getIntent().getSerializableExtra(PayConfig.INTENT_ORDER_FROM);
        String closeOrderReplay = getIntent().getStringExtra(PayConfig.INTENT_ORDER_REPAY);
        boolean posKeyTone = PreferencesUtils.getBoolean(getApplication(), BaseConfigs.BOOLEAN_POS_KEY_TONE, true);
        if (posKeyTone) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                soundPool = new SoundPool.Builder()
                        .setMaxStreams(10)
                        .build();
            } else {
                soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
            }
            if (soundPool != null) {
                soundMap = Tools.getSoundMap(soundPool, this);
            }
        }


        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        Point outSize = new Point();
        wm.getDefaultDisplay().getSize(outSize);
        width = outSize.x;

        presenter = new CashierPresenter(this, closeOrderReplay);
        btnList = new ArrayList<>(2);
        right_nav = findViewById(R.id.right_nav);
        right_nav.setText("备注");
        right_nav.setTextColor(Color.parseColor("#000000"));
        right_nav.setVisibility(View.VISIBLE);
        right_nav.setOnClickListener(this);
        rl_huabei_switch = findViewById(R.id.rl_huabei_switch);
        switch_huabei = findViewById(R.id.switch_huabei);
        ll_huabei_item = findViewById(R.id.ll_huabei_item);
        keyboard_show=findViewById(R.id.keyboard_show);
        getPermission();
        queryHuaBeiInfo();
        switch_huabei.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    String total = edt_total.getText().toString();
                    if (!TextUtils.isEmpty(total)) {
                        BigDecimal bigTotal = new BigDecimal(total);
                        if (bigTotal.floatValue() >= 100) {
                            ll_huabei_item.setVisibility(View.VISIBLE);
                            setHuaBeiItem(total);
                        } else {
                            request_pay.setHbfqNum("");
                            Toast.makeText(CashierActivity.this, "金额大于等于100元时可用", Toast.LENGTH_SHORT).show();
                            switch_huabei.setCheckedImmediatelyNoEvent(false);
                        }
                    } else {
                        request_pay.setHbfqNum("");
                        Toast.makeText(CashierActivity.this, "请输入金额", Toast.LENGTH_SHORT).show();
                        switch_huabei.setCheckedImmediatelyNoEvent(false);
                    }
                } else {
                    request_pay.setHbfqNum("");
                    ll_huabei_item.setVisibility(View.GONE);
                }
            }
        });
        String key_Style = PreferencesUtils.getString(this, BaseConfigs.PREF_KEY_STYLE, "支持金额计算");
        if ("支持金额计算".equals(key_Style)) {
            keyS = 1;
        } else {
            keyS = 0;
        }
        //初始化键盘
        initKeyBoard(keyS);
        view_bottom = findViewById(R.id.view_bottom);
        findViewById(R.id.back_nav).setOnClickListener(this);
        title = findViewById(R.id.title_nav);


        cashierLayout = findViewById(R.id.cashier_input_layout);
        edt_total = findViewById(R.id.input_total);

        ll_no_discount = findViewById(R.id.ll_no_discount);

        tv_count_num = findViewById(R.id.tv_count_num);
        String shopName = PreferencesUtils.getString(this, BaseConfigs.PREF_CASH_SHOPNAME, "");
        if (shopName.length() > 8) {
            shopName = shopName.substring(0, 8) + "...";
        }
        if (shopName.length() > 0) {
            title.setText(shopName);
        } else {
            title.setText(getString(R.string.title_pay));
        }
        int shopNum = PreferencesUtils.getInt(getApplication(), BaseConfigs.PREF_CASH_SHOPNUM, 0);
        if (shopNum > 0) {
            Drawable sdas = getResources().getDrawable(R.drawable.ic_keyboard_arrow_down_black_24dp);
            title.setCompoundDrawablesWithIntrinsicBounds(null, null, sdas, null);
            title.setOnClickListener(this);
        }
        Boolean pos_no_discount = PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_POS_NO_DISCOUNT, true);
        if (pos_no_discount) {
            ll_no_discount.setVisibility(View.VISIBLE);
        } else {
            ll_no_discount.setVisibility(View.GONE);
        }
        orderType = PayConfig.TYPE_ORDER_DEAL;
        request_pay = new Request_Pay();
        request_pay.setOrderType(orderType);
        cashierLayout.setVisibility(View.VISIBLE);

        if (!TextUtils.isEmpty(closeOrderReplay)) {
            edt_total.setText(closeOrderReplay);
            edt_total.setSelection(closeOrderReplay.length());
            keyboard.setExpression(closeOrderReplay);
            isClickable = true;

        }
        edt_total.setOnTouchListener(this);
        edt_total.addTextChangedListener(presenter.textWatcher(true));

        edt_unsale = findViewById(R.id.input_unsale);
        edt_unsale.addTextChangedListener(presenter.textWatcher(false));

        edt_unsale.setOnTouchListener(this);
        if (keyS == 1) {
            keyboard.attachTo(tv_count_num, edt_total);
        } else {
            keyboard.attachTo(null, edt_total);
        }
        keyboard.setOnHideClickListener(new KeyboardUtil.OnHideClickListener() {
            @Override
            public void onHideClick() {
                //
                keyboard_show.setVisibility(View.VISIBLE);
            }
        });
        keyboard_show.setOnClickListener(this);
        keyboard.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {
                long currentTime = Calendar.getInstance().getTimeInMillis();
                if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                    lastClickTime = currentTime;
                } else {
                    return;
                }
                //没有扫码付款权限 弹出提示
                if (!listPermission.contains(PayConfig.TYPE_PAY_SCAN_STR)) {
                    finishDialog("", "暂未开通收款方式", "知道了");
                    return;
                }

                //无可支付门店
                if (payTypes == null || payTypes.length == 0) {
                    finishDialog("", "请完成支付开通功能后重试", "知道了");
                    return;
                }

                if (!setParameter()) {
                    return;
                }
                // 扫码支付
                Intent intent = new Intent(context, ScanpayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
                intent.putExtras(bundle);
                startActivity(intent);



            }

        });

        /**
         * RxBus -- 支付成功之后，关闭栈内此页面
         */
        RxBus.with(this).setEvent(Events.PAY_COMPETE_TO_CLOSE).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (Events.PAY_COMPETE_TO_CLOSE.equals(events.getContent())) {
                    finish();
                }
            }
        }).create();

        String cash_paytypes = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_CASH_PAYTYPES, "");
        if (!TextUtils.isEmpty(cash_paytypes)) {
            payTypes = cash_paytypes.split("#");
        }

    }

    /**
     * 初始化键盘相关
     *
     * @param type 键盘类型  0 普通键盘 1 加法键盘
     */
    private void initKeyBoard(int type) {
        keyboard = new KeyboardUtil(this, type == 0 ? R.xml.keyboardnumber_paytype_1 : R.xml.keyboardnumber_paytype_count_1, "收款", "清空", listPermission, true);
        if (type == 0) {
            keyboard.setOnOkClickValue(keyClickOne);
        } else {
            keyboard.setOnOkClickValue(keyClickTwo);
        }

    }
    private String oldMsg;
    private KeyboardUtil.OnOkClickValue keyClickOne = new KeyboardUtil.OnOkClickValue() {
        @Override
        public void onOkClickVal(String value, EditText edit) {
            String txt = edit.getText().toString();
            if (txt.equals(oldMsg)) {
                keyboardVoicePlay("click");
            } else {
                keyboardVoicePlay(value);
                oldMsg = txt;
            }
        }
    };

    private KeyboardUtil.OnOkClickValue keyClickTwo = new KeyboardUtil.OnOkClickValue() {
        @Override
        public void onOkClickVal(String value, EditText edit) {
            edit.setSelection(edit.getText().toString().length());
            keyboardVoicePlay(value);
        }
    };


    @Override
    protected void onDestroy() {
        if (soundPool != null) {
            soundPool.release();
        }
        super.onDestroy();
    }

    /**
     * 支付所需参数
     *
     * @return 是否成功
     */
    private boolean setParameter() {
        if (PayConfig.TYPE_ORDER_DEAL.equals(orderType)) {
            if (!isClickable) {
                Tools.showToast(context, "请输入收款金额");
                edt_total.requestFocus();
                if (keyS == 1) {
                    keyboard.attachTo(tv_count_num, edt_total);
                } else {
                    keyboard.attachTo(null, edt_total);
                }
                return false;
            }
            String totalAmount = Tools.getSafeString(edt_total.getText().toString());
            String unsaleAmount = Tools.getSafeString(edt_unsale.getText().toString());
            double unsaleFloat = 0;
            double totalFloat = 0;
            try {
                if (!TextUtils.isEmpty(unsaleAmount)) {
                    unsaleFloat = Double.valueOf(unsaleAmount);
                }
                if (!TextUtils.isEmpty(totalAmount)) {
                    totalFloat = Double.valueOf(totalAmount);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (!TextUtils.isEmpty(totalAmount) && unsaleFloat <= totalFloat) {
                if (!TextUtils.isEmpty(unsaleAmount)) {
                    if (unsaleAmount.contains(".")) {
                        request_pay.setUndiscountableAmount(String.valueOf(Float.valueOf(unsaleAmount)));
                    } else {
                        request_pay.setUndiscountableAmount(unsaleAmount);
                    }
                } else {
                    request_pay.setUndiscountableAmount("0");
                }
                if (totalAmount.contains(".")) {
                    request_pay.setTotalAmount(new BigDecimal(totalAmount).toString());
                } else {
                    request_pay.setTotalAmount(totalAmount);
                }
            } else {
                Tools.showToast(context, "不参与优惠金额要小于消费总金额！");
                return false;
            }
        }
        return true;
    }


    private void setHuaBeiItem(String total1) {
        BigDecimal total = new BigDecimal(total1);
        final List<HUABEIAMORTIZEBean> list = extInfo.getHUABEI_AMORTIZE();
        tv_huabei1 = findViewById(R.id.tv_huabei1);
        tv_huabei2 = findViewById(R.id.tv_huabei2);
        tv_huabei3 = findViewById(R.id.tv_huabei3);
        tv_huabei4 = findViewById(R.id.tv_huabei4);

        tv_huabei1.setTextColor(Color.parseColor("#FF211A"));
        tv_huabei2.setTextColor(Color.parseColor("#333333"));
        tv_huabei3.setTextColor(Color.parseColor("#333333"));
        tv_huabei4.setTextColor(Color.parseColor("#333333"));

        if (list.size() >= 1) {
            tv_huabei1.setVisibility(View.VISIBLE);
            String[] result = getEveryIssueSumTotal(total, list.get(0).getHbfqNum(), list.get(0).getFeeRate());
            tv_huabei1.setText("¥" + result[1] + "/期×" + list.get(0).getHbfqNum() + "期\n其中手续费¥" + result[0] + "/期");
            tv_huabei1.setOnClickListener(this);
            tv_huabei1.setBackgroundResource(R.drawable.shape_tip_bg_huabei_red);
            tv_huabei1.setTag(list.get(0).getHbfqNum());
            request_pay.setHbfqNum(list.get(0).getHbfqNum());
        }
        if (list.size() >= 2) {
            String[] result = getEveryIssueSumTotal(total, list.get(1).getHbfqNum(), list.get(1).getFeeRate());
            tv_huabei2.setVisibility(View.VISIBLE);
            tv_huabei2.setText("¥" + result[1] + "/期×" + list.get(1).getHbfqNum() + "期\n其中手续费¥" + result[0] + "/期");
            tv_huabei2.setOnClickListener(this);
            tv_huabei2.setTag(list.get(1).getHbfqNum());
            tv_huabei2.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
        }

        if (list.size() >= 3) {
            tv_huabei3.setVisibility(View.VISIBLE);
            String[] result = getEveryIssueSumTotal(total, list.get(2).getHbfqNum(), list.get(2).getFeeRate());
            tv_huabei3.setText("¥" + result[1] + "/期×" + list.get(2).getHbfqNum() + "期\n其中手续费¥" + result[0] + "/期");
            tv_huabei3.setOnClickListener(this);
            tv_huabei3.setTag(list.get(2).getHbfqNum());
            tv_huabei3.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
        }

        if (list.size() >= 4) {
            tv_huabei4.setVisibility(View.VISIBLE);
            String[] result = getEveryIssueSumTotal(total, list.get(3).getHbfqNum(), list.get(3).getFeeRate());
            tv_huabei4.setText("¥" + result[1] + "/期×" + list.get(3).getHbfqNum() + "期\n其中手续费¥" + result[0] + "/期");
            tv_huabei4.setOnClickListener(this);
            tv_huabei4.setTag(list.get(3).getHbfqNum());
            tv_huabei4.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
        }

    }


    /**
     * 获取每期总费用（每期本金加手续费）
     *
     * @param payAmount 总费用
     * @param num       期数
     * @param feeRate   费率
     * @return 每期总费用（每期本金加手续费）和手续费  result[0] 手续费 result[1] 总费用
     */
    private String[] getEveryIssueSumTotal(BigDecimal payAmount, String num, String feeRate) {
        String[] result = new String[2];
        //每期本金
        BigDecimal eachPrin = payAmount.divide(new BigDecimal(num), 2, BigDecimal.ROUND_DOWN);
        //每期手续费
        BigDecimal totalFeeInDecimal = payAmount.multiply(new BigDecimal(feeRate));
        BigDecimal eachFee = totalFeeInDecimal.divide(new BigDecimal(num), 2, BigDecimal.ROUND_DOWN);
        result[0] = eachFee.toString();
        //每期总费用（每期本金加手续费）
        BigDecimal prinAndFee = eachFee.add(eachPrin);
        result[1] = prinAndFee.toString();
        return result;
    }

    /**
     * 根据用户权限和其他业务逻辑判断隐藏相关功能模块
     */
    private void getPermission() {
        listPermission = new ArrayList<>();
        listPermission.add(PayConfig.TYPE_PAY_SCAN_STR);
    }

    private void getHuabeiInfo() {
        //是否包含花呗分期权限
        String PREFS_STR_EXTINFO = PreferencesUtils.getString(this, BaseConfigs.PREFS_STR_EXTINFO, "");
        if (TextUtils.isEmpty(PREFS_STR_EXTINFO)) {
            rl_huabei_switch.setVisibility(View.GONE);
        } else {
            extInfo = new Gson().fromJson(PREFS_STR_EXTINFO, HuabeiService.class);
            if (extInfo == null || extInfo.getHUABEI_AMORTIZE().size() == 0) {
                rl_huabei_switch.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 获取花呗信息
     */
    private void queryHuaBeiInfo() {
        String shopId = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREF_CASH_SHOPID, "");
        if (!TextUtils.isEmpty(shopId)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("shopId", shopId);
            NetWorkRequset.queryHuaBeiInfo(map, new MySubscriber() {
                @Override
                public void onSuccess(Response_Base response_baseModel) {
                    if (response_baseModel.getCode().equals("1")) {
                        HuabeiService serviceExtBean = (HuabeiService) response_baseModel.getResultObject();
                        if (serviceExtBean != null) {
                            extInfo = serviceExtBean;
                            if (extInfo == null || extInfo.getHUABEI_AMORTIZE().size() == 0) {
                                rl_huabei_switch.setVisibility(View.GONE);
                            } else {
                                rl_huabei_switch.setVisibility(View.VISIBLE);
                            }
                        } else {
                            rl_huabei_switch.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onNeedLogin(String msg) {
                }

                @Override
                public void onFail(Response_Base response_baseModel) {
                    //出现错误用登录获取信息
                    getHuabeiInfo();
                }
            });
        } else {
            rl_huabei_switch.setVisibility(View.GONE);
        }
    }

    /**
     * 设置默认支付门店
     *
     */
    private void saveAndUpdateCommonConfig(String shopId) {
        showLoading("加载中,请稍候...");
        if (!TextUtils.isEmpty(shopId)) {
            Request_SetShopPay request_setShopPay = new Request_SetShopPay();
            request_setShopPay.setShopId(shopId);
            request_setShopPay.setType("app_pay");
            NetWorkRequset.saveAndUpdateCommonConfig(request_setShopPay, new MySubscriber() {
                @Override
                public void onSuccess(Response_Base response_baseModel) {
                    dismissLoading();
                    if (response_baseModel.getCode().equals("1")) {
                        title.setText(shopsBean.getShopName());
                        PreferencesUtils.putString(MyApplication.application, BaseConfigs.PREF_CASH_SHOPID, shopsBean.getShopId());
                        PreferencesUtils.putString(MyApplication.application, BaseConfigs.PREF_CASH_SHOPNAME, shopsBean.getShopName());
                        HuabeiService huabeiService = shopsBean.getHuabeiService();
                        if (huabeiService != null && huabeiService.getHUABEI_AMORTIZE() != null && huabeiService.getHUABEI_AMORTIZE().size() > 0) {
                            PreferencesUtils.putString(
                                    MyApplication.application,
                                    BaseConfigs.PREFS_STR_EXTINFO, new Gson().toJson(huabeiService));
                            extInfo = huabeiService;
                            rl_huabei_switch.setVisibility(View.VISIBLE);
                        } else {
                            PreferencesUtils.putString(MyApplication.application,
                                    BaseConfigs.PREFS_STR_EXTINFO, "");
                            extInfo = null;
                            rl_huabei_switch.setVisibility(View.GONE);
                            ll_huabei_item.setVisibility(View.GONE);
                            request_pay.setHbfqNum("");
                        }
                        int[] payTypes = shopsBean.getPayTypes();
                        if (payTypes != null && payTypes.length > 0) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = payTypes.length - 1; i >= 0; i--) {
                                stringBuilder.append(payTypes[i]).append("#");
                            }
                            PreferencesUtils.putString(CashierActivity.this, BaseConfigs.PREF_CASH_PAYTYPES, stringBuilder.toString());

                        }
                    }
                }

                @Override
                public void onNeedLogin(String msg) {
                    dismissLoading();
                }

                @Override
                public void onFail(Response_Base response_baseModel) {
                    dismissLoading();
                    if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                        Toast.makeText(CashierActivity.this, response_baseModel.getMsg(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        } else {
            rl_huabei_switch.setVisibility(View.GONE);
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.input_total) {
            if (keyS == 1) {
                keyboard.attachTo(tv_count_num, edt_total);
                keyboard.setOnOkClickValue(keyClickTwo);
            } else {
                keyboard.attachTo(null, edt_total);
                keyboard.setOnOkClickValue(keyClickOne);
            }

        }
        if (v.getId() == R.id.input_unsale) {
            keyboard.attachTo(null, edt_unsale);
            keyboard.setOnOkClickValue(keyClickOne);
        }

        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back_nav) {
            finish();
            return;
        }
        if(v.getId()==R.id.keyboard_show){
            if(keyboard_show.getVisibility()==View.VISIBLE){
                keyboard_show.setVisibility(View.GONE);
                keyboard.showKeyboard();
            }
        }

        //备注
        if (v.getId() == R.id.right_nav) {
            Intent intent = new Intent(this, CashierRemarkActivity.class);
            intent.putExtra("remark", request_pay.getRemark());
            startActivityForResult(intent, 31);
        }

        if (v.getId() == R.id.title_nav) {
            Intent intent = new Intent(new Intent(this, ChooseShopActivity.class));
            intent.putExtra("isSettingsActivity", true);
            intent.putExtra("shopPayList", "shopPayList");
            startActivityForResult(intent, Constants.SettingsActivityForResultCode);
        }

        if(v.getId() == R.id.tv_huabei1 || v.getId() == R.id.tv_huabei2
                || v.getId() == R.id.tv_huabei3 || v.getId() == R.id.tv_huabei4){
            tv_huabei1.setTextColor(Color.parseColor("#333333"));
            tv_huabei2.setTextColor(Color.parseColor("#333333"));
            tv_huabei3.setTextColor(Color.parseColor("#333333"));
            tv_huabei4.setTextColor(Color.parseColor("#333333"));

            if (v.getId() == R.id.tv_huabei1) {
                request_pay.setHbfqNum(tv_huabei1.getTag().toString());
                tv_huabei1.setBackgroundResource(R.drawable.shape_tip_bg_huabei_red);
                tv_huabei1.setTextColor(Color.parseColor("#FF211A"));
                tv_huabei2.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei3.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei4.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
            }

            if (v.getId() == R.id.tv_huabei2) {
                request_pay.setHbfqNum(tv_huabei2.getTag().toString());
                tv_huabei1.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei2.setBackgroundResource(R.drawable.shape_tip_bg_huabei_red);
                tv_huabei2.setTextColor(Color.parseColor("#FF211A"));
                tv_huabei3.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei4.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
            }

            if (v.getId() == R.id.tv_huabei3) {
                request_pay.setHbfqNum(tv_huabei3.getTag().toString());
                tv_huabei1.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei2.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei3.setBackgroundResource(R.drawable.shape_tip_bg_huabei_red);
                tv_huabei3.setTextColor(Color.parseColor("#FF211A"));
                tv_huabei4.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
            }

            if (v.getId() == R.id.tv_huabei4) {
                request_pay.setHbfqNum(tv_huabei4.getTag().toString());
                tv_huabei1.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei2.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei3.setBackgroundResource(R.drawable.shape_tip_bg_huabei_gray);
                tv_huabei4.setBackgroundResource(R.drawable.shape_tip_bg_huabei_red);
                tv_huabei4.setTextColor(Color.parseColor("#FF211A"));
            }

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 31 && resultCode == 30) {
            if (data != null) {
                String remark = data.getStringExtra("remark");
                if (TextUtils.isEmpty(remark)) {
                    remark = "";
                    request_pay.setRemark(remark);
                    Toast.makeText(this, "备注已删除", Toast.LENGTH_LONG).show();
                    return;
                }
                request_pay.setRemark(remark);
                Toast.makeText(this, "添加备注成功", Toast.LENGTH_LONG).show();
            }
        } else if (resultCode == Constants.SettingsActivityForResultCode) {
            Bundle bundle = data.getExtras();
            /**
             * ShopsBean
             * auditStatus : 4.0
             * branchShopName : 丁家屯店
             * mainShopName : 云纵测试门店
             * shopId : 2017022700077000000026808340
             * shopName : 云纵测试门店(丁家屯店)
             */
            shopsBean = (ShopListItem.ResultObjectBean.PageDataBean.ShopsBean) bundle.getSerializable("shopsBean");
            saveAndUpdateCommonConfig(shopsBean.getShopId());
        }
    }

    /**
     * 输入框是否激活状态
     *
     * @param isActive 是否是激活状态
     */
    @Override
    public void isActive(boolean isActive) {
        if (!PayConfig.TYPE_ORDER_DISH.equals(orderType)) {
            if (isActive) {
                isClickable = true;
            } else {
                isClickable = false;
            }
        }

    }

    /**
     * 输入框内容填充
     *
     * @param isTotal
     * @param text
     */
    @Override
    public void setTextInput(boolean isTotal, String text) {
        if (!PayConfig.TYPE_ORDER_DISH.equals(orderType)) {
            if (isTotal) {
                edt_total.setText(text);
            } else {
                edt_unsale.setText(text);
            }
        }

    }

    /**
     * 展示活动内容
     *
     * @param promotion
     */
    @Override
    public void showPromotion(String promotion) {
    }

    /**
     * 设置输入框光标位置
     *
     * @param isTotal 是否是总金额输入框
     * @param offset
     */
    @Override
    public void setSelection(boolean isTotal, int offset) {
        if (!PayConfig.TYPE_ORDER_DISH.equals(orderType)) {
            if (isTotal) {
                edt_total.setSelection(offset);
            } else {
                edt_unsale.setSelection(offset);
            }
        }
    }

    @Override
    public void setTextSize(int size, boolean isTotal) {
        if (!PayConfig.TYPE_ORDER_DISH.equals(orderType) && isTotal) {
//            edt_total.setTextSize(size);
        }

    }

    @Override
    public void keyboardVoicePlay(String voiceCode) {
        if (!PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_LOCAL_RECEIVABLES, true)) {
            return;
        }
        if (soundPool != null && soundMap != null) {
            if (PayConfig.TYPE_ORDER_RECHARGE.equals(request_pay.getOrderType())) {
                if ("click".equals(voiceCode)) {
                    Tools.soundMapPlay(soundMap, soundPool, voiceCode);
                }
            } else {
                Tools.soundMapPlay(soundMap, soundPool, voiceCode);
            }

        }
    }

    @Override
    public void onText(boolean isTotal, String text) {
        if (ll_huabei_item.getVisibility() == View.VISIBLE) {
            switch_huabei.setCheckedImmediately(false);
        }
    }

    @Override
    public void setPresenter(CashierContract.Presenter presenter) {
        if (null == presenter) {
            return;
        }
        this.presenter = presenter;
    }

    private void finishDialog(String title, String msg, String btnValue) {
        final PublicDialog publicDialog = new PublicDialog(this);
//        publicDialog.setIcon();
        publicDialog.setTitle(title);
        publicDialog.setMessage(msg);
        publicDialog.setRightBtn(btnValue, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                publicDialog.dismiss();
            }
        });
        publicDialog.show();
    }

    @Override
    protected void onResume() {
        if (request_pay != null && !TextUtils.isEmpty(request_pay.getHbfqNum())) {
            request_pay.setHbfqNum("");
        }
        super.onResume();
    }
}

